package com.shop.sms.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.discovery.converters.Auto;
import com.shop.sms.config.AliyunProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ghy
 * @version 1.0
 * @date 2020-10-29
 */
@RestController
@RequestMapping("/sms")
@Slf4j
public class SmsController {

    @Autowired
    private AliyunProperties aliyunProperties;

    @GetMapping("/send")
    public String send(@RequestParam("phone") String phone, @RequestParam("code") String code) {

        try {
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                    aliyunProperties.getAccessKeyId(), aliyunProperties.getAccessSecret());
            IAcsClient client = new DefaultAcsClient(profile);

            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", aliyunProperties.getSignName());
            request.putQueryParameter("TemplateCode", aliyunProperties.getTemplateCode());
            Map map = new HashMap<>();
            map.put("code", code);
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonCode = objectMapper.writeValueAsString(map);

            request.putQueryParameter("TemplateParam", jsonCode);
            CommonResponse response = client.getCommonResponse(request);
            log.info("{}", response.getData());

            return response.getData();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
